from django.shortcuts import render
from django.http import HttpResponse
from django.core.urlresolvers import reverse

# Create your views here.
from .. import models
from . viewsIndex import uploads


def goodsindex(request):
    #获取所有的用户数据
    data = models.Goods.objects.filter().exclude(status=3)

    #获取搜索条件和参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    #判断是否有搜索条件
    if types:
        #判断搜索的类型
        if types == 'all':
            #多字段的条件搜索
            from django.db.models import Q
            data = data.filter(Q(goodsname__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords)|Q(status__contains=keywords)|Q(addtime__contains=keywords))
        elif types == 'status':
            # keywords == 禁用
            arr = {'正常':0,'禁用':1,'删除':3}
            data = data.filter(status=arr[keywords])
        else:
            search = {types+'__contains':keywords}
            data = data.filter(**search)

    #数据分页
    from django.core.paginator import Paginator
    #实例化分页类 参数1,获取所有的数据对象  参数2 每页显示多少条
    paginator = Paginator(data,20)
    #获取当前页码数 ?p=n
    p = request.GET.get('p',1)
    #获取当前页的数据
    goodslist = paginator.page(p)


    #分配数据
    context = {'goodslist':goodslist}

    #加载模板
    return render(request,'myadmin/goods/index.html',context)



# 商品添加 
def goodsadd(request):
    # 获取所有的商品分类
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    # 分配数据
    context = {'cateslist':data}
    # 加载模板
    return render(request,'myadmin/goods/add.html',context)

# 执行商品添加 
def goodsinsert(request):
    # try:
        # 接受数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')

        data['cateid'] = models.Cates.objects.get(id=data['cateid'])

        # 处理上传的商品主图
        myfile = request.FILES.get('pic_url')
        if myfile:
            data['pic_url'] = uploads(myfile)
        else:
            return HttpResponse('<script>alert("必须上传商品主图");history.back(-1);</script>')

        # 执行数据的添加
        ob = models.Goods(**data)
        ob.save()
        return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    # except:
    #     return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_goods_add')+'"</script>')






